# coding: utf-8
import sys

from PySide6.QtCore import QProcess
from qfluentwidgets import MessageBoxBase, TextBrowser


class ProcessDialog(MessageBoxBase):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.process = QProcess(self)
        self.logBrowser = TextBrowser(self)

        self.process.setProcessChannelMode(QProcess.ProcessChannelMode.MergedChannels)
        if sys.platform == 'win32':
            self.process.setProgram('cmd.exe')
        elif sys.platform == 'linux':
            self.process.setProgram('bash')
        else:
            self.process.setProgram('sh')
        self.process.readyReadStandardOutput.connect(self.onReadyReadStandardOutput)
        self.process.started.connect(self.onStarted)
        self.process.finished.connect(self.onFinished)
        self.process.errorOccurred.connect(self.onError)

        self.yesButton.setVisible(False)
        self.cancelButton.setText(self.tr('关闭'))
        self.viewLayout.addWidget(self.logBrowser)
        self._hBoxLayout.removeWidget(self.widget)
        self._hBoxLayout.setContentsMargins(100, 100, 100, 100)
        self._hBoxLayout.addWidget(self.widget)

    def onReadyReadStandardOutput(self):
        data = self.process.readAllStandardOutput().toStdString()
        self.logBrowser.append(data)

    def run(self, *args, **kwargs):
        self.process.start(*args, **kwargs)

    def onStarted(self):
        self.cancelButton.setEnabled(False)

    def onFinished(self, exitCode, exitStatus):
        self.cancelButton.setEnabled(True)
        self.logBrowser.append(f'Process finished with exit code {exitCode} and exit status {exitStatus}')

    def onError(self, error):
        self.cancelButton.setEnabled(True)
        self.logBrowser.append(f'Process error: {error}')
        self.logBrowser.append(f'Process error: {error.errorString()}')
